<?php
if(!defined('MY_ROOT'))
{throw new Exception('Access Denied');}
require (MY_ROOT.'/source/class/jwxt.class.php');
require_once(MY_ROOT.'/source/class/opac.php');
class SMUWX{
	public static function event($data,&$type,&$out){
		switch($data['event']){
			case 'subscribe':
				self::welcome($data,$type,$out);
				break;
			case 'CLICK':
				self::menuclick($data,$type,$out);
				break;
			case 'VIEW':
				self::viewurl($data,$type,$out);
				break;
			default:
				self::disp("未知事件值",$type,$out);
		}
	}
	public static function cmdexec($data,&$type,&$out){
		$funcs=array('help','bdjwxt','upjwxt','kcb','booksearch','dict','tr','rentbooks','ecard');//函数列表,函数名称全部为英语，符号为英语，参数可以是中文
		if(!preg_match("/^([a-z0-9]*?)#(.*)$/",$data["content"],$m)){
			preg_match('/^(.*?)#(.*)$/',$data['content'],$m);
			if($res=DB::select('translate','`words`='.DB::get_str($m[1]),'`id`',true)){
				$func=$res['func'];
				$argc=$m[2];
				if(in_array($func,$funcs)){
				self::$func($argc,$data,$type,$out); 
				}
				else{
				self::disp("函数未找到",$type,$out);
				}
			}else{
			self::disp("输入信息非法",$type,$out);
			}
		}else{
			$func=$m[1];
			$argc=$m[2];
			if(in_array($func,$funcs)){
			self::$func($argc,$data,$type,$out); 
			}
			else{
				self::disp("函数未找到",$type,$out);
				}
			}
	}
	private static function menuclick($data,&$type,&$out){
		$key=$data['eventkey'];
		$st=DB::select("actions","`key`='".$key."'",'`id`',true);
		$type=$st['type'];
		if($type=='func'){
			list($func,$argc)=explode("#",$st['action']);
			self::$func($argc,$data,$type,$out);
		}else{
		self::response(explode(",",$st['action']),$st['type'],$out);
		}
	}
	private static function response($conts,&$type,&$out){
		if($type=='news'){
			$i=0;
			foreach($conts as $id){
				if($i>9){
				break;
				}
				$out['articles'][$i]=DB::select("news","`id`=".intval($id),"`id`",true);
				$i++;
			}
			$out['count']=$i;
		}else{
			$st=DB::select("resptext","`id`=".$conts,"`id`",true);
			$out["content"]=$st["text"];
		}
	}
	private static function disp($content,&$type,&$out){
		$type="text";
		$out["content"]=$content;
	}
	private static function welcome($data,&$type,&$out){
		$st=DB::select("actions","`key`='welcome'",'`id`',true);
		$type=$st['type'];
		self::response(explode(",",$st['action']),$st['type'],$out);
	}
	public static function prase($data,&$type,&$out){
		if(preg_match('/^(.*?)[:：]$/',$data["content"],$m)){
			$action=$m[1];
			$st=DB::select("actions","`key`=".DB::get_str($action),'`id`',true);
			$type=$st['type'];
			self::response(unserialize($st['action']),$st['type'],$out);
		}elseif(preg_match('/^[\x{4e00}-\x{9fa5}]/u',$data['content'],$m)){
			$ret=self::chn($data['content']);
			$func=$ret['func'];
			$argc=$ret['argc'];
			self::$func($argc,$data,$type,$out);
		}else{
			$ct=preg_replace('/\s(?=\s)/','',$data['content']);
			$cs=explode(" ",$ct);
			foreach ($cs as $c){
				$csa[]=mysql_escape_string($c);
			}
			$ct=implode("%' OR `keywords` LIKE '%",$csa);
			$cond="`keywords` LIKE '%".$ct."%'";
			$res=DB::select("keywords",$cond,'`id`');
			if(!$res){
				self::welcome($data,$type,$out);
				return;
			}
			$i=0;
			foreach($res as $r){
				$key[$i]=$r['content'];
				if($i<10)
					$i++;
				else
					break;
			}
			$type='news';
			self::response($key,$type,$out);
		}
	}
	private static function bdjwxt($argc,$data,&$type,&$out){
		error_reporting(0);
		list($user,$pass,$remeber)=explode('%',$argc);
		if(DB::select('wxuser','`wxid`='.DB::get_str($data['from']),'`id`',true)){
			$type='text';
			$out['content']='亲你已经绑定过了，不需要再绑定了';
			return -1;
		}
		if(!$table=jwxt::login($user,$pass)){
			$type='text';
			$out['content']='登录失败，请检查用户名与密码!';
			return -1;
		}
		$table=jwxt::getkcb($user);
		$sc=jwxt::getscore($user);
		$ds['kcb']=serialize($table);
		$ds['cjd']=serialize($sc);
		if($remember=='Y'){
			$ds['jwxt']=serialize(array('user'=>$user,'pass'=>$pass));   // Action Required 
		}else{
			$ds['jwxt']=serialize(array('user'=>$suer));
			}
		$ds['wxid']=$data['from'];
		DB::insert('wxuser',$ds);
		$type='text';
		$out['content']='绑定成功！';
	}
	private static function upjwxt($argc,$data,&$type,&$out){
		error_reporting(0);
		if(!$res=DB::select('wxuser','`wxid`='.DB::get_str($data['from']),'`id`',true)){
			$type='text';
			$out['content']='亲你没有绑定过教务系统呢！请使用bdjwxt语句';
			return -1;
		}else{
			if($res['jwxt']!=""){list($user,$pass)=unserialize($res['jwxt']);}
			else{
				list($user,$pass,$remeber)=explode('%',$argc);
				}
			}
		if(!$table=jwxt::login($user,$pass)){
			$type='text';
			$out['content']='登录失败，请检查用户名与密码!';
			return -1;
		}
		$table=jwxt::getkcb($user);
		$sc=jwxt::getscore($user);
		$ds['kcb']=serialize($table);
		$ds['cjd']=serialize($sc);
		if($remember=='Y'){
			$ds['jwxt']=serialize(array('user'=>$user,'pass'=>$pass));   // Action Required 
		}
		$wh='`wxid`='.DB::get_str($data['from']);
		DB::update('wxuser',$ds,$wh);
		$type='text';
		$out['content']='数据已更新';
	}
	private static function kcb($argc,$data,&$type,&$out){
		$ds=DB::select('wxuser','`wxid`='.DB::get_str($data['from']),'`id`',true);
		if(!$ds){
			$type='text';
			$out['content']='亲,你还没绑定教务系统呢！ 回复help查看帮助';
			return -2;
		}
		$table=unserialize($ds['kcb']);
		$ts=1410710400;
		if($ts>time()){
			$type="text";
			$out['content']="本学期尚未开始";
			return;
		}
		$wk=(int) ((time()-$ts)/604800+1);
		$dt=date('N',time());
		if(preg_match('/@(\d+)/',$argc,$m)) {//周数
			//$wk=str_replace("@","",$m[0]);
			$wk=$m[1];
			unset($m);
		}
		if(preg_match('/%(\d)/',$argc,$m)) {//星期
			//$dt=str_replace("%","",$m[0]);
			$dt=$m[1];
			unset($m);
		}
		
		if(preg_match('/:(\w{1,})/',$argc,$m)){
			//$str=str_replace(':',"",$m[0]);
			$str=$m[1];
			switch($str){
				case 'tomorrow':
					$dt+=1;
					if($dt>7){
					$dt=$dt%7;
					$wk++;
					}

					break;
				case 'dat':
					$dt+=2;
					if($dt>7){
					$dt=$dt%7;
					$wk++;}
					break;
			}
		}
		$st=1;
		$ed=13;
		if(preg_match('/[!！](\w{1,})/',$argc,$m)){
			
			switch($m[1]){
				case 'morning':
					$ed=4;
					break;
				case 'afternoon':
					$st=7;
					$ed=10;
					break;
				case 'evening':
					$st=11;
					$ed=13;
					break;
			}
		}
		
		$dt-=1;
		$dt=(string)$dt;
		$content="";
		//var_dump($table);
		foreach( $table[$dt] as $num=>$days){
			foreach($days as $day){
			if($day['week'][$wk]==1){
				//$day['num']=intval($num)+1;
				$db[intval($num)+1]=$day;
				//$content.="第".(intval($num)+1)."节|".$day['name']."|".$day['place']."\n";
			}}
		}
		
		for ($i=$st;$i<=$ed;$i++){
			if(isset($db[$i])){$content.="第".(intval($i))."节|".$db[$i]['name']."|".$db[$i]['place']."\n";}
			else{continue;}
		}
		$out['count']=2;
		$out['articles']=array(array('title'=>'第'.$wk.'周星期'.num2cn($dt+1).'课表','picurl'=>0,'desc'=>'   ','url'=>''),
							   array('title'=>$content,'desc'=>'','url'=>'','picurl'=>0));
		$type='news';
		
	}
	private static function help($argc,$data,&$type,&$out){
		switch($argc){
			case 'opac':
				self::disp("图书馆查询方法:\n搜索书目回复booksearch#书名",$type,$out);
				break;
			default:
				self::disp("感谢由Ken Chu提供的技术支持，此功能尚未完善或者您输入的语句无法识别，请与开发者联系\n",$type,$out);
		}
	}
	private static function nextc($argc,$data,&$type,&$out){
		$t=time();
		if($t<=strtotime("Today 08:20")){
			$class=0; //第一节课前
		}
		elseif($t<=strtotime("Today 9:10")){
			$class=1;
		}
		elseif($t<=strtotime("Today 10:15")){
			$class=2;
		}
		elseif($t<=strtotime("Today11:05")){
			$class=3;
		}
		elseif($t<=strtotime("Today 13:10")){
			$class=6; //下午
		}
		elseif($t<=strtotime("Today 14:00")){
			$class=7;
		}
		elseif($t<=strtotime("Today 15:05")){
			$class=8;
		}
		elseif($t<=strtotime("Today 15:55")){
			$class=9;
		}
		elseif($t<=strtotime("Today 18:00")){
			$class=10;
		}
		elseif($t<=strtotime("Today 18:50")){
			$class=11;
		}
		elseif($t<=strtotime("Today 19:40")){
			$class=12;
		}
		else{
			$out['content']="亲，今天已经没有课了，早点休息吧！";
			$type='text';
			return;
			}
		$ds=DB::select('wxuser','`wxid`='.DB::get_str($data['from']),'`id`',true);
		if(!$ds){
			$type='text';
			$out['content']='亲,你还没绑定教务系统呢！ 回复help查看帮助';
			return -2;
		}
		$table=unserialize($ds['kcb']);
		$ts=1410710400;
		$wk=(int) (($t-$ts)/604800+1);
		$dt=date('N',$t);
		$cs=$table[$dt-1][$class];
		$out['content']='下节没课';
		$type="text";
		foreach($cs as $c){
			if($c['week'][$wk]==1){
				//$day['num']=intval($num)+1;
				$out['content']='下节课：由'.$c['teacher'].'在'.$c['place'].'上'.$c['name'];
				//$content.="第".(intval($num)+1)."节|".$day['name']."|".$day['place']."\n";
			}
		}
		
		return;
	}//下节课
	private static function chn($cin){
		if(preg_match('/：/',$cin)){list($func,$argc)=explode('：',$cin);}
		elseif(preg_match('/:/',$cin)){list($func,$argc)=explode(':',$cin);}
		else{
		$cin=urlencode($cin);
		$cin=preg_replace("/(%7E|%60|%21|%40|%23|%24|%25|%5E|%26|%27|%2A|%28|%29|%2B|%7C|%5C|%3D|\-|_|%5B|%5D|%7D|%7B|%3B|%22|%3A|%3F|%3E|%3C|%2C|\.|%2F|%A3%BF|%A1%B7|%A1%B6|%A1%A2|%A1%A3|%A3%AC|%7D|%A1%B0|%A3%BA|%A3%BB|%A1%AE|%A1%AF|%A1%B1|%A3%FC|%A3%BD|%A1%AA|%A3%A9|%A3%A8|%A1%AD|%A3%A4|%A1%A4|%A3%A1|%E3%80%82|%EF%BC%81|%EF%BC%8C|%EF%BC%9B|%EF%BC%9F|%EF%BC%9A|%E3%80%81|%E2%80%A6%E2%80%A6|%E2%80%9D|%E2%80%9C|%E2%80%98|%E2%80%99)+/",'',$cin);  //去除标点符号
		$cin=urldecode($cin);
		$delws=array("有什么","是什么","需要","啥","什么","的");
		$cin=str_replace($delws,"",$cin);
		$func=$cin;
		}
		$res=DB::select('translate','`words`='.DB::get_str($func),'`id`',true);
		if(!$res){
			//*************课程表处理开始*********//
			if(preg_match('/课$/',$cin)){
				$ret['func']='kcb';
				if(preg_match('/^(.*?)天(.*?)课$/',$cin,$m)){
					switch($m[1]){
						case '明':
							$argc=':tomorrow';
							break;
						case '后':
							$argc=':dat';
							break;
						default:
							$ret['func']='disp';
							$ret['argc']='亲，现在只支持明后天哦！';
							return $ret;
					}
					switch($m[2]){
						case '上午':
							$argc.='!morning';
							break;
						case '下午':
							$argc.='!afternoon';
							break;
						case '':
							break;
						default:
							$ret['func']='disp';
							$ret['argc']='现在不能识别该语句';
							return $ret;
					}
				}
				elseif(preg_match('/^(.*?)周(.{3})(.*?)课$/',$cin,$m)){
					
					$argc="";
					switch($m[1]){
						case '本':
						case '这':
							break;
						case '下':
							$ts=1410710400;
							$wk=(int)((time()-$ts)/604800+1);
							$wk++;
							$argc.="@".$wk;
							break;
						default:
							if(preg_match("/^第(\d+)/",$m[1],$ma)){
								$wk=$ma[1];
								$argc.="@".$wk;
							}
					}
					switch($m[2]){
						case '一':
							$argc.="%1";
							break;
						case '二':
							$argc.="%2";
							break;
						case '三':
							$argc.="%3";
							break;
						case '四':
							$argc.="%4";
							break;
						case '五':
							$argc.="%5";
							break;
						case '六':
							$argc.="%6";
							break;
						case '日':
						case '天':
							$argc.="%7";
							break;
						default:
							$ret['func']='disp';
							$ret['argc']='现在不能识别该语句';
							return $ret;
							break;
					}
					switch($m[3]){
						case '上午':
							$argc.='!morning';
							break;
						case '下午':
							$argc.='!afternoon';
							break;
						case '晚上':
							$argc.='!evening';
							break;
						case '':
							break;
						default:
							$ret['func']='disp';
							$ret['argc']='现在不能识别该语句';
							return $ret;
					}
				}
			}
			//************课程表处理结束**********//
			elseif(preg_match('/书$/',$cin)){
				
			}
			/*********按关键字查找内容************/
			else{
				$ct=preg_replace('/\s(?=\s)/','',$data['content']);
			$cs=explode(" ",$ct);
			foreach ($cs as $c){
				$csa[]=mysql_escape_string($c);
			}
			$ct=implode("%' OR `keywords` LIKE '%",$csa);
			$cond="`keywords` LIKE '%".$ct."%'";
			$res=DB::select("keys",$cond,'`id`');
			if(!$res){
				$ret['func']='help';
				$ret['argc']='';
				return $ret;
			}
			$i=0;
			foreach($res as $r){
				$key[$i]=$r['content'];
				if($i<10)
					$i++;
				else
					break;
			}
			$type='news';
			self::response($key,$type,$out);
			}
			//****************按关键字查找结束**********/
		}
		else{
			$ret['func']=$res['func'];
			if($res['argc']!=""){$argc=$res['argc'];}
		}
		$ret['argc']=isset($argc) ? $argc : '';
		return $ret;
	}//中文解析结束
	private static function score($argc,$data,&$type,&$out){
		$ds=DB::select('wxuser','`wxid`='.DB::get_str($data['from']),'`id`',true);
		if(!$ds){
			$type='text';
			$out['content']='亲,你还没绑定教务系统呢！ 回复help查看帮助';
			return -2;
		}
		$sc=unserialize($ds['cjd']);
		$content="";
		
		foreach($sc as $score){
			$content.="课程名称:".$score['name']." 最终成绩:".$score['score']." 绩点:".$score['gp']."\n";
		}
		if($content==""){$content="没有本学期成绩记录或者缓存未更新，请使用upjwxt更新";}
		$type="news";
		$out['count']=3;
		$out['articles']=array(array('title'=>'本学期成绩','picurl'=>0,'desc'=>'   ','url'=>''),
		array('title'=>$content,'picurl'=>0,'desc'=>'   ','url'=>''),
		array('title'=>'Powered By Z-WX<<SMU','picurl'=>0,'desc'=>'   ','url'=>'http://www.greatqq.com/?s=wechat'));
	}//成绩查询
	private static function booksearch($argc,$data,&$type,&$out){
		$bys=array('title','isbn','author','subject','class','ctrlno','orderno','publisher','callno');
		if(preg_match('/^(.*?):(.*?)$/',$argc,$m)){
			$by=in_array(trim($m[1]),$bys) ? trim($m[1]) : 'title';
			$name=$m[2];
		}
		else{
			$by='title';
			$name=trim($argc);
			}
		$result=opac::search($name,$by);
		$type='news';
		$i=1;
		$out['articles'][0]['title']=$name."OPAC查询结果";
		foreach ($result as $book){
		if($i>=10){
			break;
		}
		$t="名称：".$book['title']."\n";
		$t.="作者：".$book['author']."\n";
		$t.="出版社：".$book['publisher']."\n";
		$t.="索书号：".$book['callno']."\n";
		$t.="馆藏位置：".$book['place']."\n";
		$t.="查询号：".$book['id'];
		$out['articles'][$i]['title']=$t;
		$out['articles'][$i]['url']="http://58.40.126.44:8080/opac/book/".$book['id'];
		$i++;
		}
		$out['count']=$i;
		return;
	}//图书查询
	private static function dict($argc,$data,&$type,&$out){
		$ch=curl_init();
		$url="http://dict-co.iciba.com/api/dictionary.php?key=F552117CD972772C5F4A881D76222827&type=json&w=".$argc;
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
		$res=curl_exec($ch);
		$sa=json_decode($res,true);
		if(isset($sa['symbols'][0]['parts'])){
			$content="";
			foreach($sa['symbols'][0]['parts'] as $part){
				$content.="词性:".$part["part"].":\n";
				$i=0;
				foreach($part['means'] as $mean){
					$content.=$i.$mean."\n";
					$i++;
				}
			}
		}else{
			$content="单词未找到";
			}
		$type='news';
		$out['count']=3;
		$out['articles']=array(array('title'=>"单词：".$argc.'查询结果','picurl'=>0,'desc'=>'','url'=>''),
		array('title'=>$content,'picurl'=>0,'desc'=>'   ','url'=>''),
		array('title'=>"以上信息由爱词霸提供\nPowered By Z-WX<<SMU\n",'picurl'=>0,'desc'=>'   ','url'=>'http://www.greatqq.com/?s=wechat'));
	}//爱词霸
	private function tr($argc,$data,&$type,&$out){
		$url="http://openapi.baidu.com/public/2.0/bmt/translate?client_id=9oIqowhyeDXjWbFpI9hmON7o&from=auto&to=auto&q=".urlencode($argc);
		$ch=curl_init($url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
		$res=curl_exec($ch);
		$sa=json_decode($res,true);
		if(isset($sa['error_code'])){
		$content="接口错误错误信息:".$sa['error_msg'];	
		}else{
			$content="";
			foreach($sa['trans_result'] as $tr){
				$content.=$tr['dst']."\n";
			}
		}
		$content=trim($content);
		$type='news';
		$out['count']=3;
		$out['articles']=array(array('title'=>"翻译结果",'picurl'=>0,'desc'=>'','url'=>''),
		array('title'=>$content,'picurl'=>0,'desc'=>'   ','url'=>''),
		array('title'=>"以上信息由百度翻译提供\nPowered By Z-WX<<SMU",'picurl'=>0,'desc'=>'   ','url'=>'http://www.greatqq.com/?s=wechat'));
	}
	private static function rentbooks($argc,$data,&$type,&$out){
		if($argc==""){
		if(!$res=DB::select('wxuser','`wxid`='.DB::get_str($data['from']),'`id`',true)){
			$type='text';
			$out['content']='账户未登陆，请先绑定教务系统';
			return -1;
		}
		$r=unserialize($res['jwxt']);
		$id=$r['user'];}else{$id=$argc;}
		$res=opac::rentbook($id);
		if($res['retcode']!=0)
		{
			$type='text';
			$out['content']='查询失败';
			return;
		}
		$content="";
		foreach($res['bookinfos'] as $r)
		{
			$content.="书名：".$r['title'];
			$content.="还书日期：".$r['returndate'];
		}
		$type='news';
		$out['count']=3;
		$out['articles']=array(array('title'=>"图书馆借书目录",'picurl'=>0,'desc'=>'','url'=>''),
		array('title'=>$content,'picurl'=>0,'desc'=>'   ','url'=>''),
		array('title'=>"Powered By Z-WX<<SMU",'picurl'=>0,'desc'=>'   ','url'=>'http://www.greatqq.com/?s=wechat'));
	}
	private static function ecard($argc,$data,&$type,&$out){
		error_reporting(E_ALL);
		if($argc==""){
		if(!$res=DB::select('wxuser','`wxid`='.DB::get_str($data['from']),'`id`',true)){
			$type='text';
			$out['content']='账户未登陆，请先绑定教务系统';
			return -1;
		}
		$r=unserialize($res['jwxt']);
		$id=$r['user'];}else{$id=$argc;}
		$str1=date("Y-m-d H:i:s");
		$str2=md5($id.$str1."f54d48bae4282389688919e34e470cab");
		$url="http://m.shmtu.edu.cn/mobile/hsydpt/sjjk/YKT_JBXXs";
		$parm="stuempno=".$id."&sign=".$str2."&sendtime=".urlencode($str1);
		$ch=curl_init();
		curl_setopt($ch,CURLOPT_URL,$url."?".$parm);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36');
		$res=curl_exec($ch);
		$r=json_decode($res,true);
		if($r['retcode']!=0){
			$type='text';
			$out['content']=$r['msg'];
			return;
		}
		$content="学号：".$r['data']['stuempno']."\n姓名：".$r['data']['custname']."\n余额：".$r['data']['balance'];
		$type='news';
		$out['count']=3;
		$out['articles']=array(array('title'=>"一卡通查询结果",'picurl'=>0,'desc'=>'','url'=>''),
		array('title'=>$content,'picurl'=>0,'desc'=>'   ','url'=>''),
		array('title'=>"Powered By Z-WX<<SMU",'picurl'=>0,'desc'=>'   ','url'=>'http://www.greatqq.com/?s=wechat'));
	}
}